package dk.mirasola.systemtraining.user.server.service;

import com.google.appengine.api.datastore.Email;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import dk.mirasola.systemtraining.server.entity.Suggest;
import dk.mirasola.systemtraining.user.shared.service.UserService;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class UserServiceImpl extends RemoteServiceServlet implements UserService {
    @Override
    public void addSuggestEmails(Set<String> emails) {
        if (emails == null || emails.size() == 0) {
            return;
        }
        Objectify ofy = ObjectifyService.begin();
        Suggest userSuggest = findUserSuggest(ofy);

        if (userSuggest == null) {
            List<Email> e = new ArrayList<Email>();
            for (String email : emails) {
                e.add(new Email(email));
            }
            userSuggest = new Suggest(UserServiceFactory.getUserService().getCurrentUser().getEmail());
            userSuggest.setEmails(e);
        } else {
            for (String email : emails) {
                userSuggest.getEmails().add(0,new Email(email));
            }

            while (userSuggest.getEmails().size() > 50) {
                userSuggest.getEmails().remove(50);
            }
        }
        ofy.put(userSuggest);
    }

    @Override
    public List<String> getEmailSuggest() {
        List<String> res = new ArrayList<String>();
        Objectify ofy = ObjectifyService.begin();
        Suggest userSuggest = findUserSuggest(ofy);
        if (userSuggest != null) {
            for (Email email : userSuggest.getEmails()) {
                res.add(email.getEmail());
            }
        }
        return res;
    }

    private Suggest findUserSuggest(Objectify ofy) {
        return ofy.find(Suggest.class, UserServiceFactory.getUserService().getCurrentUser().getEmail());
    }
}
